<template>
  <div
    :id="'editor' + Date.now()"
    ref="editorRef"
    :style="{ height: height + 'px' }"
    class="ra-wang-editor"
  ></div>
</template>

<script setup>
import E from 'wangeditor';
import { ref, watch, onMounted, onBeforeUnmount, nextTick } from 'vue';
import UploadAPI from '@/api/admin/upload';
import { debounce } from 'lodash-es';
import { useSettingsStore } from '@/store';
import { ThemeEnum } from '@/enums';

const settingsStore = useSettingsStore();
const props = defineProps({
  modelValue: {
    type: String,
    default: '',
  },
  height: {
    type: String,
    default: '400',
  },
});

const emit = defineEmits(['update:modelValue']);

const editorRef = ref(null);
const editor = ref(null);
let lastRange = null;

// 防抖更新
const emitUpdate = debounce((html) => {
  emit('update:modelValue', html);
}, 300);

// 主题切换方法
const toggleTheme = () => {
  const container = document.querySelector('.w-e-text-container');
  const toolbar = document.querySelector('.w-e-toolbar');

  if (settingsStore.theme === ThemeEnum.DARK) {
    container.style.backgroundColor = '#1a1a1a';
    container.style.color = '#e0e0e0';
    toolbar.style.backgroundColor = '#2d2d2d';
  } else {
    container.style.backgroundColor = '';
    container.style.color = '';
    toolbar.style.backgroundColor = '';
  }
};

// 初始化编辑器配置
const initEditor = () => {
  editor.value = new E(editorRef.value);

  editor.value.config.zIndex = 9999;

  // 基础配置
  editor.value.config.uploadImgMaxLength = 1;
  editor.value.config.uploadFileName = 'file';
  editor.value.config.uploadImgAccept = [
    'jpg',
    'jpeg',
    'png',
    'gif',
    'bmp',
    'webp',
  ];
  editor.value.config.uploadImgMaxSize = 10 * 1024 * 1024;
  editor.value.config.uploadImgServer = '#';

  // 内容变化回调
  editor.value.config.onchange = (html) => {
    lastRange = editor.value.selection.getRange();
    emitUpdate(html);
  };

  // 自定义图片上传
  editor.value.config.customUploadImg = (resultFiles, insertImgFn) => {
    const formdata = new FormData();
    formdata.append('file', resultFiles[0]);
    formdata.append('edit', 1);
    UploadAPI.upload(formdata).then(({ data }) => {
      insertImgFn(data.url);
    });
  };

  // 创建编辑器
  editor.value.create();

  // 初始内容设置
  if (props.modelValue) {
    editor.value.txt.html(props.modelValue);
  }

  // 初始主题设置
  toggleTheme();
};

// 监听内容变化（父组件更新）
watch(
  () => props.modelValue,
  (newVal) => {
    if (!editor.value) return;

    // 内容不一致时更新
    if (newVal !== editor.value.txt.html()) {
      // 禁用change事件
      const tempOnChange = editor.value.config.onchange;
      editor.value.config.onchange = null;

      // 保存光标位置
      const selection = window.getSelection();
      lastRange = selection.rangeCount > 0 ? selection.getRangeAt(0) : null;

      // 更新内容
      editor.value.txt.html(newVal);

      // // 恢复光标
      // if (lastRange) {
      //   selection.removeAllRanges();
      //   selection.addRange(lastRange);
      // }

      // // 恢复事件监听
      // setTimeout(() => {
      //   editor.value.config.onchange = tempOnChange;
      // }, 50);
    }
  },
);

// 监听主题变化
watch(
  () => settingsStore.theme,
  () => {
    nextTick(toggleTheme);
  },
);

onMounted(() => {
  nextTick(initEditor);
});

onBeforeUnmount(() => {
  if (editor.value) {
    editor.value.destroy();
    editor.value = null;
  }
});
</script>

<style lang="scss" scoped>
.ra-wang-editor {
  margin: 5px;
  padding: 5px;
  width: 100%;
}
</style>
